package com.appspot.didit.client;

import com.appspot.didit.client.statistic.StatisticPresenter;
import com.appspot.didit.client.tag.TagManagePresenter;
import com.appspot.didit.client.tag.TagService;
import com.appspot.didit.client.tag.TagServiceAsync;
import com.appspot.didit.client.tag.TagSharePresenter;
import com.appspot.didit.client.user.LoginPresenter;
import com.appspot.didit.client.user.LoginSuccessEvent;
import com.appspot.didit.client.user.LoginSuccessHandler;
import com.appspot.didit.client.user.LogoutEvent;
import com.appspot.didit.client.user.LogoutHandler;
import com.appspot.didit.client.user.RegisterPresenter;
import com.appspot.didit.client.user.User;
import com.appspot.didit.client.user.UserManager;
import com.appspot.didit.client.user.UserService;
import com.appspot.didit.client.user.UserServiceAsync;
import com.appspot.didit.client.workitem.WorkitemExportPresenter;
import com.appspot.didit.client.workitem.WorkitemManagePresenter;
import com.extjs.gxt.ui.client.widget.MessageBox;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.FocusEvent;
import com.google.gwt.event.dom.client.FocusHandler;
import com.google.gwt.event.logical.shared.SelectionEvent;
import com.google.gwt.event.logical.shared.SelectionHandler;
import com.google.gwt.event.shared.HandlerManager;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.DecoratedTabPanel;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.inject.Inject;

public class MainPresenterImpl implements MainPresenter {

	private final View view;
	private final UserServiceAsync userService = GWT.create(UserService.class);
	private final TagServiceAsync tagService = GWT.create(TagService.class);
	private final LoginPresenter loginPresenter;

	private final RegisterPresenter registerPresenter;

	private final WorkitemManagePresenter wmPresenter;

	private final WorkitemExportPresenter wePresenter;

	private final TagManagePresenter tmPresenter;

	private final TagSharePresenter tsPresenter;

	private final StatisticPresenter stPresenter;

	private final HandlerManager eventBus;

	@Inject
	public MainPresenterImpl(final HandlerManager eventBus, final LoginPresenter loginPresenter,
			final RegisterPresenter registerPresenter, WorkitemManagePresenter wmPresenter,
			WorkitemExportPresenter wePresenter, TagManagePresenter tmPresenter, TagSharePresenter tsPresenter,
			StatisticPresenter stPresenter, final View view) {

		this.view = view;

		this.loginPresenter = loginPresenter;

		this.registerPresenter = registerPresenter;

		this.wmPresenter = wmPresenter;

		this.wePresenter = wePresenter;

		this.tmPresenter = tmPresenter;

		this.tsPresenter = tsPresenter;

		this.stPresenter = stPresenter;

		this.eventBus = eventBus;
			
		bindEvents(eventBus);
	}

	private void bindEvents(HandlerManager eventBus) {

		eventBus.addHandler(LoginSuccessEvent.getType(), new LoginSuccessHandler() {
			public void onLoginSuccess(LoginSuccessEvent event) {
				initUI();
			}
		});
		eventBus.addHandler(LogoutEvent.getType(), new LogoutHandler() {
			public void onLogout(LogoutEvent event) {
				doLogout();
			}
		});

	}

	protected void doLogout() {
		redirect("http://didit-tool.appspot.com/");
	}

	@SuppressWarnings("unchecked")
	private void initUI() {
		view.hideLogin();
		String url = getParamString();
		if (url.startsWith("?s")) {
			tagService.share(url.substring(2), UserManager.getInstance().getUser().getUsername(), new AsyncCallback() {
				public void onFailure(Throwable caught) {
					GWT.log("Failed to check the Validity of Username, Exception thrown", caught);
				}

				public void onSuccess(Object result) {
					// View aktualisieren
					redirect("http://didit-tool.appspot.com/DidIt.html");
					GWT.log("Tag shared!", null);
				}
			});
		}
		System.out.println(url.startsWith("?i"));
		System.out.println(url);
		if (url.startsWith("?i")) {
			tagService.acceptInvitation(url.substring(2), UserManager.getInstance().getUser().getUsername(),
					new AsyncCallback() {
						public void onFailure(Throwable caught) {
							GWT.log("Failed to check the Validity of Username, Exception thrown", caught);
						}

						public void onSuccess(Object result) {
							// View aktualisieren
							redirect("http://didit-tool.appspot.com/DidIt.html");
							GWT.log("Tag Invitation accepted!", null);
						}
					});
		}
		view.addWorkitemManage(wmPresenter.getView());
		view.addTagShare(tsPresenter.getView());
		view.addTagManage(tmPresenter.getView());
		view.addStatistic(stPresenter.getView());
		view.addWorkitemExport(wePresenter.getView());
		view.addUserInfo();
		view.getTabPanel().addSelectionHandler(new SelectionHandler() {

			@Override
			public void onSelection(SelectionEvent event) {
				DecoratedTabPanel tabPanel = view.getTabPanel();
				if (event.getSelectedItem() == (Integer) (tabPanel.getWidgetCount() - 1)) {
					final MessageBox box = MessageBox.wait("Abmelden", "Abmelden, bitte warten...", "Abmelden...");
					userService.logout(new AsyncCallback() {
						public void onFailure(Throwable caught) {
							GWT.log("Login failed, Exception thrown", caught);
						}

						public void onSuccess(Object result) {
							GWT.log("User Logout!", null);
							redirect("http://didit-tool.appspot.com/DidIt.html");
							box.close();
						}
					});
				}

			}

		});
		/*
		 * userInfoPresenter.updateUserInfo();
		 * view.showUserInfo(userInfoPresenter.getView());
		 */
	}

	@SuppressWarnings("unchecked")
	public void go(final RootPanel rootPanel) {
		rootPanel.setVisible(false);
		userService.getUser(new AsyncCallback() {
			public void onFailure(Throwable caught) {
				GWT.log("Login failed, Exception thrown", caught);
			}

			public void onSuccess(Object result) {
				if (result != null) {
					UserManager.getInstance().setUser((User) result);
					rootPanel.add(view.getWidget());
					eventBus.fireEvent(new LoginSuccessEvent());
					// initUI();
				} else {
					view.addLogin(loginPresenter.getView());
        	    	view.addRegister(registerPresenter.getView());
        	        rootPanel.add(view.getWidget());
        	        userService.init(new AsyncCallback() {
            			@Override
            			public void onFailure(Throwable caught) {}
            			@Override
            			public void onSuccess(Object result) {}
                	});
				}
				rootPanel.setVisible(true);
				RootPanel.get("loading").setVisible(false);
			}
		});

	}

	public BaseView getView() {
		return view;
	}

	private native String getParamString() /*-{
											return $wnd.location.search;
											}-*/;

	public static native void redirect(String url)/*-{
													$wnd.location = url;
													}-*/;

}